#include "../include/main_account.hh"
#include "../include/main_utils.hh"
#include <iomanip>
#include <limits>

// 显示账户信息
void displayAccountInfo(const std::shared_ptr<Account>& account) {
    if (account) {
        std::cout << "账户ID: " << account->getAccountId() << std::endl;
        std::cout << "账户持有人: " << account->getOwnerName() << std::endl;
        std::cout << "当前余额: " << std::endl;
        std::cout << "  人民币(CNY): ¥" << std::fixed << std::setprecision(2) << account->getBalance(Currency::CNY) << std::endl;
        std::cout << "  美元(USD): $" << std::fixed << std::setprecision(2) << account->getBalance(Currency::USD) << std::endl;
        std::cout << "  欧元(EUR): €" << std::fixed << std::setprecision(2) << account->getBalance(Currency::EUR) << std::endl;
    }
}

// 处理转账操作的辅助函数
bool handleTransferOperation(BankSystem& bankSystem, UIManager& uiManager, 
                            const std::string& sourceAccountId) {
    auto sourceAccount = bankSystem.findAccountById(sourceAccountId);
    if (!sourceAccount) {
        std::string errorMessage;
        if (uiManager.getCurrentLanguage() == Language::ENGLISH) {
            errorMessage = "Error: Source account does not exist.";
        } else if (uiManager.getCurrentLanguage() == Language::FRENCH) {
            errorMessage = "Erreur: Le compte source n'existe pas.";
        } else {
            errorMessage = "错误：源账户不存在。";
        }
        std::cout << errorMessage << std::endl;
        return false;
    }
    
    displayAccountInfo(sourceAccount);
    std::cout << std::endl;
    
    // 获取账户所有者
    std::string ownerName = sourceAccount->getOwnerName();
    auto owner = bankSystem.findCustomerByName(ownerName);
    if (!owner) {
        std::string errorMessage;
        if (uiManager.getCurrentLanguage() == Language::ENGLISH) {
            errorMessage = "Error: Cannot find account owner.";
        } else if (uiManager.getCurrentLanguage() == Language::FRENCH) {
            errorMessage = "Erreur: Impossible de trouver le propriétaire du compte.";
        } else {
            errorMessage = "错误：无法找到账户所有者。";
        }
        std::cout << errorMessage << std::endl;
        return false;
    }
    
    // 密码验证提示
    std::string passwordPrompt, invalidPasswordError;
    
    if (uiManager.getCurrentLanguage() == Language::ENGLISH) {
        passwordPrompt = "Please enter account password for verification: ";
        invalidPasswordError = "Error: Incorrect password, transaction cancelled.";
    } else if (uiManager.getCurrentLanguage() == Language::FRENCH) {
        passwordPrompt = "Veuillez entrer le mot de passe du compte pour vérification: ";
        invalidPasswordError = "Erreur: Mot de passe incorrect, transaction annulée.";
    } else {
        passwordPrompt = "请输入账户密码进行验证: ";
        invalidPasswordError = "错误：密码不正确，交易已取消。";
    }
    
    // 密码验证
    std::string password = uiManager.getInput(passwordPrompt);
    if (!owner->verifyPassword(password)) {
        std::cout << invalidPasswordError << std::endl;
        return false;
    }
    
    // 其他的转账流程文本
    std::string destAccountPrompt, amountPrompt, notePrompt, invalidAmountError;
    std::string transferSuccess, transferFailed;
    
    if (uiManager.getCurrentLanguage() == Language::ENGLISH) {
        destAccountPrompt = "Please enter destination account ID (full account number): ";
        amountPrompt = "Please enter transfer amount: ";
        notePrompt = "Add note (optional): ";
        invalidAmountError = "Invalid amount, transfer cancelled.";
        transferSuccess = "Transfer successful!";
        transferFailed = "Transfer failed.";
    } else if (uiManager.getCurrentLanguage() == Language::FRENCH) {
        destAccountPrompt = "Veuillez entrer l'ID du compte de destination (numéro de compte complet): ";
        amountPrompt = "Veuillez entrer le montant du transfert: ";
        notePrompt = "Ajouter une note (facultatif): ";
        invalidAmountError = "Montant invalide, transfert annulé.";
        transferSuccess = "Transfert réussi!";
        transferFailed = "Le transfert a échoué.";
    } else {
        destAccountPrompt = "请输入目标账户ID（完整账号）: ";
        amountPrompt = "请输入转账金额: ";
        notePrompt = "添加备注 (可选): ";
        invalidAmountError = "无效金额，转账取消。";
        transferSuccess = "转账成功！";
        transferFailed = "转账失败。";
    }
    
    std::string destAccountId = uiManager.getInput(destAccountPrompt);
    
    // 选择货币
    std::string currencyPrompt, CNYOption, USDOption, EUROption;
    
    if (uiManager.getCurrentLanguage() == Language::ENGLISH) {
        currencyPrompt = "Select transfer currency:";
        CNYOption = "1. Chinese Yuan (CNY)";
        USDOption = "2. US Dollar (USD)";
        EUROption = "3. Euro (EUR)";
    } else if (uiManager.getCurrentLanguage() == Language::FRENCH) {
        currencyPrompt = "Sélectionnez la devise de transfert:";
        CNYOption = "1. Yuan chinois (CNY)";
        USDOption = "2. Dollar américain (USD)";
        EUROption = "3. Euro (EUR)";
    } else {
        currencyPrompt = "请选择转账货币：";
        CNYOption = "1. 人民币 (CNY)";
        USDOption = "2. 美元 (USD)";
        EUROption = "3. 欧元 (EUR)";
    }
    
    std::cout << currencyPrompt << std::endl;
    std::cout << CNYOption << std::endl;
    std::cout << USDOption << std::endl;
    std::cout << EUROption << std::endl;
    
    Currency selectedCurrency = Currency::CNY;
    int currencyChoice = uiManager.getMenuChoice(1, 3);
    
    switch (currencyChoice) {
        case 1:
            selectedCurrency = Currency::CNY;
            break;
        case 2:
            selectedCurrency = Currency::USD;
            break;
        case 3:
            selectedCurrency = Currency::EUR;
            break;
    }
    
    std::string currencySymbol = CurrencyConverter::getCurrencySymbol(selectedCurrency);
    std::string currencyName = CurrencyConverter::getCurrencyName(selectedCurrency);
    
    // 修改提示，包含货币信息
    if (uiManager.getCurrentLanguage() == Language::ENGLISH) {
        amountPrompt = "Please enter transfer amount (" + currencySymbol + "): ";
    } else if (uiManager.getCurrentLanguage() == Language::FRENCH) {
        amountPrompt = "Veuillez entrer le montant du transfert (" + currencySymbol + "): ";
    } else {
        amountPrompt = "请输入转账金额 (" + currencySymbol + "): ";
    }
    
    double amount;
    std::cout << amountPrompt;
    std::cin >> amount;
    if (std::cin.fail() || amount <= 0) {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << invalidAmountError << std::endl;
        return false;
    }
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    
    std::string note = uiManager.getInput(notePrompt);
    
    if (bankSystem.transfer(sourceAccountId, destAccountId, amount, selectedCurrency, note)) {
        std::cout << transferSuccess << std::endl;
        
        // 更新显示文本，让它反映当前使用的货币
        if (uiManager.getCurrentLanguage() == Language::ENGLISH) {
            std::cout << "Source account new balance:" << std::endl;
        } else if (uiManager.getCurrentLanguage() == Language::FRENCH) {
            std::cout << "Nouveau solde du compte source:" << std::endl;
        } else {
            std::cout << "源账户新余额:" << std::endl;
        }
        
        std::cout << "  人民币(CNY): ¥" << std::fixed << std::setprecision(2) << sourceAccount->getBalance(Currency::CNY) << std::endl;
        std::cout << "  美元(USD): $" << std::fixed << std::setprecision(2) << sourceAccount->getBalance(Currency::USD) << std::endl;
        std::cout << "  欧元(EUR): €" << std::fixed << std::setprecision(2) << sourceAccount->getBalance(Currency::EUR) << std::endl;
        return true;
    } else {
        std::cout << transferFailed << std::endl;
        return false;
    }
}

// 处理存款操作的辅助函数
bool handleDepositOperation(BankSystem& bankSystem, UIManager& uiManager, 
                           const std::string& accountId) {
    auto account = bankSystem.findAccountById(accountId);
    if (!account) {
        std::cout << "错误：账户不存在。" << std::endl;
        return false;
    }
    
    if (!account->canDeposit()) {
        std::cout << "该账户类型不支持直接存款操作。" << std::endl;
        return false;
    }
    
    displayAccountInfo(account);
    std::cout << std::endl;
    
    // 获取账户所有者
    std::string ownerName = account->getOwnerName();
    auto owner = bankSystem.findCustomerByName(ownerName);
    if (!owner) {
        std::cout << "错误：无法找到账户所有者。" << std::endl;
        return false;
    }
    
    // 密码验证
    std::string password = uiManager.getInput("请输入账户密码进行验证: ");
    if (!owner->verifyPassword(password)) {
        std::cout << "错误：密码不正确，操作已取消。" << std::endl;
        return false;
    }
    
    // 选择货币
    std::cout << "请选择存款货币：" << std::endl;
    std::cout << "1. 人民币 (CNY)" << std::endl;
    std::cout << "2. 美元 (USD)" << std::endl;
    std::cout << "3. 欧元 (EUR)" << std::endl;
    
    Currency selectedCurrency = Currency::CNY;
    int currencyChoice = uiManager.getMenuChoice(1, 3);
    
    switch (currencyChoice) {
        case 1:
            selectedCurrency = Currency::CNY;
            break;
        case 2:
            selectedCurrency = Currency::USD;
            break;
        case 3:
            selectedCurrency = Currency::EUR;
            break;
    }
    
    std::string currencySymbol = CurrencyConverter::getCurrencySymbol(selectedCurrency);
    std::string currencyName = CurrencyConverter::getCurrencyName(selectedCurrency);
    
    double amount;
    std::cout << "请输入存款金额(" << currencySymbol << "): ";
    std::cin >> amount;
    if (std::cin.fail() || amount <= 0) {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "无效金额，操作取消。" << std::endl;
        return false;
    }
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    
    std::string note = uiManager.getInput("添加备注 (可选): ");
    
    if (bankSystem.deposit(accountId, amount, selectedCurrency, note)) {
        std::cout << "存款成功！已存入" << currencyName << " " << currencySymbol << std::fixed << std::setprecision(2) << amount << std::endl;
        std::cout << "新余额: " << std::endl;
        std::cout << "  人民币(CNY): ¥" << std::fixed << std::setprecision(2) << account->getBalance(Currency::CNY) << std::endl;
        std::cout << "  美元(USD): $" << std::fixed << std::setprecision(2) << account->getBalance(Currency::USD) << std::endl;
        std::cout << "  欧元(EUR): €" << std::fixed << std::setprecision(2) << account->getBalance(Currency::EUR) << std::endl;
        return true;
    } else {
        std::cout << "存款失败。" << std::endl;
        return false;
    }
}

// 处理取款操作的辅助函数
bool handleWithdrawOperation(BankSystem& bankSystem, UIManager& uiManager, 
                            const std::string& accountId) {
    auto account = bankSystem.findAccountById(accountId);
    if (!account) {
        std::cout << "错误：账户不存在。" << std::endl;
        return false;
    }
    
    if (!account->canWithdraw()) {
        std::cout << "该账户类型不支持直接取款操作。" << std::endl;
        return false;
    }
    
    displayAccountInfo(account);
    std::cout << std::endl;
    
    // 获取账户所有者
    std::string ownerName = account->getOwnerName();
    auto owner = bankSystem.findCustomerByName(ownerName);
    if (!owner) {
        std::cout << "错误：无法找到账户所有者。" << std::endl;
        return false;
    }
    
    // 密码验证
    std::string password = uiManager.getInput("请输入账户密码进行验证: ");
    if (!owner->verifyPassword(password)) {
        std::cout << "错误：密码不正确，操作已取消。" << std::endl;
        return false;
    }
    
    // 选择货币
    std::cout << "请选择取款货币：" << std::endl;
    std::cout << "1. 人民币 (CNY)" << std::endl;
    std::cout << "2. 美元 (USD)" << std::endl;
    std::cout << "3. 欧元 (EUR)" << std::endl;
    
    Currency selectedCurrency = Currency::CNY;
    int currencyChoice = uiManager.getMenuChoice(1, 3);
    
    switch (currencyChoice) {
        case 1:
            selectedCurrency = Currency::CNY;
            break;
        case 2:
            selectedCurrency = Currency::USD;
            break;
        case 3:
            selectedCurrency = Currency::EUR;
            break;
    }
    
    std::string currencySymbol = CurrencyConverter::getCurrencySymbol(selectedCurrency);
    std::string currencyName = CurrencyConverter::getCurrencyName(selectedCurrency);
    
    double amount;
    std::cout << "请输入取款金额(" << currencySymbol << "): ";
    std::cin >> amount;
    if (std::cin.fail() || amount <= 0) {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "无效金额，操作取消。" << std::endl;
        return false;
    }
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    
    std::string note = uiManager.getInput("添加备注 (可选): ");
    
    if (bankSystem.withdraw(accountId, amount, selectedCurrency, note)) {
        std::cout << "取款成功！已取出" << currencyName << " " << currencySymbol << std::fixed << std::setprecision(2) << amount << std::endl;
        std::cout << "新余额: " << std::endl;
        std::cout << "  人民币(CNY): ¥" << std::fixed << std::setprecision(2) << account->getBalance(Currency::CNY) << std::endl;
        std::cout << "  美元(USD): $" << std::fixed << std::setprecision(2) << account->getBalance(Currency::USD) << std::endl;
        std::cout << "  欧元(EUR): €" << std::fixed << std::setprecision(2) << account->getBalance(Currency::EUR) << std::endl;
        return true;
    } else {
        std::cout << "取款失败。" << std::endl;
        return false;
    }
}

// 处理显示所有银行账户
void handleDisplayAllAccounts(BankSystem& bankSystem, UIManager& uiManager) {
    clearScreen();
    bankSystem.displayAllAccounts();
    uiManager.getInput("\n按回车键返回主菜单...");
}

// 处理账户操作
void handleAccountOperations(BankSystem& bankSystem, UIManager& uiManager, const std::string& accountId) {
    auto account = bankSystem.findAccountById(accountId);
    if (!account) {
        std::cout << "错误：账户 " << accountId << " 不存在。" << std::endl;
        uiManager.getInput("按回车键继续...");
        return;
    }
    
    while (true) {
        clearScreen();
        std::cout << "===== 银行账户: " << accountId << " =====" << std::endl;
        std::cout << "账户持有人: " << account->getOwnerName() << std::endl;
        std::cout << "余额: " << std::endl;
        std::cout << "  人民币(CNY): ¥" << std::fixed << std::setprecision(2) << account->getBalance(Currency::CNY) << std::endl;
        std::cout << "  美元(USD): $" << std::fixed << std::setprecision(2) << account->getBalance(Currency::USD) << std::endl;
        std::cout << "  欧元(EUR): €" << std::fixed << std::setprecision(2) << account->getBalance(Currency::EUR) << std::endl << std::endl;
        
        std::cout << "1. 存款" << (account->canDeposit() ? "" : " (不可用)") << std::endl;
        std::cout << "2. 取款" << (account->canWithdraw() ? "" : " (不可用)") << std::endl;
        std::cout << "3. 转账" << std::endl;
        std::cout << "4. 货币兑换" << std::endl;
        std::cout << "5. 查看交易历史" << std::endl;
        std::cout << "6. 生成账户报告" << std::endl;
        std::cout << "7. 申请关闭账户" << std::endl;
        std::cout << "8. 返回客户页面" << std::endl;
        
        int choice = uiManager.getMenuChoice(1, 8);
        
        if (choice == 8) { // 返回客户页面
            break;
        }
        
        // 处理选择
        switch (choice) {
            case 1: // 存款
                clearScreen();
                std::cout << "===== 存款操作 =====" << std::endl << std::endl;
                handleDepositOperation(bankSystem, uiManager, accountId);
                uiManager.getInput("按回车键继续...");
                break;
                
            case 2: // 取款
                clearScreen();
                std::cout << "===== 取款操作 =====" << std::endl << std::endl;
                handleWithdrawOperation(bankSystem, uiManager, accountId);
                uiManager.getInput("按回车键继续...");
                break;
                
            case 3: { // 转账
                clearScreen();
                std::cout << "===== 从账户转账: " << accountId << " =====" << std::endl << std::endl;
                
                bool transferResult = handleTransferOperation(bankSystem, uiManager, accountId);
                
                uiManager.getInput("按回车键继续...");
                break;
            }
                
            case 4: { // 货币兑换
                clearScreen();
                std::cout << "===== 货币兑换 =====" << std::endl << std::endl;
                
                // 显示账户信息
                displayAccountInfo(account);
                std::cout << std::endl;
                
                // 获取账户所有者
                std::string ownerName = account->getOwnerName();
                auto owner = bankSystem.findCustomerByName(ownerName);
                if (!owner) {
                    std::cout << "错误：无法找到账户所有者。" << std::endl;
                    uiManager.getInput("按回车键继续...");
                    break;
                }
                
                // 密码验证
                std::string password = uiManager.getInput("请输入账户密码进行验证: ");
                if (!owner->verifyPassword(password)) {
                    std::cout << "错误：密码不正确，操作已取消。" << std::endl;
                    uiManager.getInput("按回车键继续...");
                    break;
                }
                
                // 选择源货币
                std::cout << "请选择源货币：" << std::endl;
                std::cout << "1. 人民币 (CNY)" << std::endl;
                std::cout << "2. 美元 (USD)" << std::endl;
                std::cout << "3. 欧元 (EUR)" << std::endl;
                
                Currency fromCurrency = Currency::CNY;
                int fromChoice = uiManager.getMenuChoice(1, 3);
                
                switch (fromChoice) {
                    case 1:
                        fromCurrency = Currency::CNY;
                        break;
                    case 2:
                        fromCurrency = Currency::USD;
                        break;
                    case 3:
                        fromCurrency = Currency::EUR;
                        break;
                }
                
                // 选择目标货币
                std::cout << "请选择目标货币：" << std::endl;
                std::cout << "1. 人民币 (CNY)" << std::endl;
                std::cout << "2. 美元 (USD)" << std::endl;
                std::cout << "3. 欧元 (EUR)" << std::endl;
                
                Currency toCurrency = Currency::CNY;
                int toChoice = uiManager.getMenuChoice(1, 3);
                
                switch (toChoice) {
                    case 1:
                        toCurrency = Currency::CNY;
                        break;
                    case 2:
                        toCurrency = Currency::USD;
                        break;
                    case 3:
                        toCurrency = Currency::EUR;
                        break;
                }
                
                if (fromCurrency == toCurrency) {
                    std::cout << "错误：源货币和目标货币不能相同！" << std::endl;
                    uiManager.getInput("按回车键继续...");
                    break;
                }
                
                std::string fromSymbol = CurrencyConverter::getCurrencySymbol(fromCurrency);
                
                // 输入兑换金额
                double amount;
                std::cout << "请输入兑换金额(" << fromSymbol << "): ";
                std::cin >> amount;
                if (std::cin.fail() || amount <= 0) {
                    std::cin.clear();
                    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
                    std::cout << "无效金额，操作取消。" << std::endl;
                    uiManager.getInput("按回车键继续...");
                    break;
                }
                std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
                
                // 显示手续费信息
                std::cout << "注意：货币兑换将收取1%的手续费。" << std::endl;
                
                // 获取备注
                std::string note = uiManager.getInput("添加备注 (可选): ");
                
                // 执行货币兑换
                if (account->exchangeCurrency(fromCurrency, toCurrency, amount, note)) {
                    std::cout << "货币兑换成功！" << std::endl;
                } else {
                    std::cout << "货币兑换失败，请检查余额是否充足。" << std::endl;
                }
                
                uiManager.getInput("按回车键继续...");
                break;
            }
                
            case 5: { // 查看交易历史
                clearScreen();
                std::cout << "===== 账户 " << accountId << " 的交易历史 =====" << std::endl << std::endl;
                
                const auto& transactions = account->getTransactionHistory();
                if (transactions.empty()) {
                    std::cout << "该账户尚无交易记录。" << std::endl;
                } else {
                    for (const auto& transaction : transactions) {
                        transaction.display();
                    }
                }
                
                uiManager.getInput("按回车键继续...");
                break;
            }
                
            case 6: { // 生成账户报告
                if (bankSystem.generateAccountReport(accountId)) {
                    std::cout << "已成功生成账户报告！" << std::endl;
                } else {
                    std::cout << "生成报告失败。" << std::endl;
                }
                
                uiManager.getInput("按回车键继续...");
                break;
            }
                
            case 7: { // 申请关闭账户
                clearScreen();
                std::cout << "===== 关闭账户申请 =====" << std::endl << std::endl;
                
                std::cout << "账户信息:" << std::endl;
                displayAccountInfo(account);
                std::cout << std::endl;
                
                // 确认关闭
                std::string confirm = uiManager.getInput("警告：关闭账户后无法恢复！是否继续? (Y/N): ");
                if (toupper(confirm[0]) != 'Y') {
                    std::cout << "关闭操作已取消。" << std::endl;
                    uiManager.getInput("按回车键继续...");
                    break;
                }
                
                // 获取客户密码
                std::string password = uiManager.getInput("请输入账户密码确认关闭: ");
                
                if (bankSystem.deleteAccount(accountId, account->getOwnerName(), password)) {
                    std::cout << "账户已成功关闭。" << std::endl;
                    uiManager.getInput("按回车键返回...");
                    return; // 账户已删除，直接返回
                } else {
                    uiManager.getInput("按回车键继续...");
                }
                break;
            }
        }
    }
} 